package com.dhcc.bpm.common.utils.http;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * Company 东华软件股份公司
 * Author: nihaobo
 * Date:  2020/08/20 20:36
 * Description:
 */
public class HttpClientUtil {

    /**
     * 功能描述: <http-post通讯>
     *
     * @Param: [url, json, connectionRequestTimeout, connectTimeout, socketTimeout]
     * @Return: com.dhcc.commons.util.httpclient.HttpClientResult
     * @Author: nihaobo
     * @Date: 2020/8/21
     */
    public static HttpClientResult doPostJson(String url, String json, int connectionRequestTimeout, int connectTimeout, int socketTimeout) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);

        if (json != null) {
            // 构造一个请求实体
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            return new HttpClientResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } catch (ConnectException connException) {
            return new HttpClientResult(505,
                    Status.COMMUNICATE_CONNECT_REFUSED_ERROR.getMsg() + "。请求路径:[ " + url+" ]");
        } catch (SocketTimeoutException socketException) {
            return new HttpClientResult(506,
                    Status.COMMUNICATE_THIRD_PARTY_TIMEOUT_ERROR.getMsg() + "。超时等待时间" + socketTimeout + "ms,请求路径:[ " + url+" ]");
        } catch (ConnectTimeoutException timeOutException) {
            return new HttpClientResult(507,
                    Status.COMMUNICATE_CONNECT_TIMEOUT_ERROR.getMsg() + "。超时等待时间" + connectTimeout + "ms,请求路径:[ " + url+" ]");
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
    }


}
